<?php

namespace App\Services;

use React\EventLoop\Factory;
use React\Socket\Server;
use React\Socket\ConnectionInterface;

class TelnetServer
{
    protected $loop;
    protected $socket;
    protected $commandHandler;

    public function __construct(CommandHandler $commandHandler, $host = '127.0.0.1', $port = 8765)
    {
        $this->commandHandler = $commandHandler;
        $this->host = $host;
        $this->port = $port;
    }

    public function start()
    {
        $this->loop = Factory::create();
        $this->socket = new Server("{$this->host}:{$this->port}", $this->loop);

        $this->socket->on('connection', function (ConnectionInterface $connection) {
            $this->handleConnection($connection);
        });

        echo "Telnet Server running on {$this->host}:{$this->port}\n";
        echo "Using advanced input filtering\n";
        $this->loop->run();
    }

    protected function handleConnection(ConnectionInterface $connection)
    {
        $connection->write("Telnet Server\n");
        $connection->write("Commands: mul, incr, div, conv_tree, help, exit\n");
        $connection->write("> ");

        $buffer = '';

        $connection->on('data', function ($data) use ($connection, &$buffer) {
            $buffer .= $data;

            if (strpos($buffer, "\n") !== false) {
                $lines = explode("\n", $buffer);
                
                // 只处理第一个完整行
                $line = $lines[0];
                if (!empty(trim($line))) {
                    $this->processCommand($connection, $line);
                }
                
                $buffer = count($lines) > 1 ? $lines[1] : '';
                $connection->write("> ");
            }
        });
    }

    protected function processCommand(ConnectionInterface $connection, $input)
    {
        // 使用新的输入过滤器提取命令
        $result = InputFilter::extractCommand($input);
        $command = $result['command'];
        $arguments = $result['arguments'];

        if (empty($command)) {
            $connection->write("No valid command found\n");
            return;
        }

        $output = $this->commandHandler->handle($command, $arguments);
        $connection->write($output . "\r\n");
    }

    public function stop()
    {
        if ($this->socket) {
            $this->socket->close();
        }
        if ($this->loop) {
            $this->loop->stop();
        }
    }
}